package tice.twitterwalk.List;

import java.util.ArrayList;

import tice.twitterwalk.App;
import tice.twitterwalk.R;
import tice.twitterwalk.DB.DBTweetsHelper;
import tice.twitterwalk.Util.TwitterItem;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class TweetsCursorAdapter extends CursorAdapter{
	
	public App _App = null;
	
    public class ViewHolder {
    	TextView title;
    	TextView text;
    	TextView timesource;
    	ImageView icon;
    	LinearLayout itemline;
    	LinearLayout imagelayout;
    	ImageView unread;
    	ProgressBar progressbar;
    	ImageView favorite;
    	ImageView conversation;
    }
	
    boolean mInRefresh = false;
    Bitmap mFav, mUnFav, mBlank, mUnRead, mConversation;
    TweetsListActivity  mCtx;
	private int mListbackground;
	private int mListbackgroundat;
	private int mListbackgroundmy;
	private int mListbackgroundselset;
	private int mtextviewcolor;
	private int mtextviewcolorselect;
	private int mScrollState;
	private int mLoadingState = 0;
	private ArrayList<Integer> mReadStatuses = new ArrayList<Integer>();
	private MatrixCursor mCursor;
    
	public TweetsCursorAdapter(Context context, MatrixCursor c) {
		super(context, c);

    	_App = (App)context.getApplicationContext();
    	
        mCtx = (TweetsListActivity)context;
        
        mFav = BitmapFactory.decodeResource(context.getResources(), R.drawable.star_on);
        mUnFav = BitmapFactory.decodeResource(context.getResources(), R.drawable.star_off);
        mBlank = BitmapFactory.decodeResource(context.getResources(), R.drawable.default_profile_1_normal);
        mUnRead = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_sms_unread_msg_indicator);
        mConversation = BitmapFactory.decodeResource(context.getResources(), R.drawable.conversationt);
        
	    TypedArray atts = context.obtainStyledAttributes(new int []
	                                  {R.attr.ListViewBackground,	R.attr.ListViewBackgroundAt,
	                                   R.attr.ListViewBackgroundMy, R.attr.ListViewBackgroundSelect,
	                                   R.attr.TextViewColor, R.attr.TextViewColorSelect});
	    
	    
	    mListbackground = atts.getResourceId(0, R.drawable.theme_default_listbackground);
	    mListbackgroundat = atts.getResourceId(1, R.drawable.theme_default_listbackgroundat);
	    mListbackgroundmy = atts.getResourceId(2, R.drawable.theme_default_listbackgroundmy);
	    mListbackgroundselset = atts.getResourceId(3, R.drawable.theme_default_listbackgroundselect);
	    mtextviewcolor = atts.getColor(4, 0xff313031);
	    mtextviewcolorselect = atts.getColor(5, 0xff313031);
	    
	    atts.recycle();
	    
	    mCursor = c;
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
        
		final LayoutInflater inflater = LayoutInflater.from(context);
		final View view = inflater.inflate(R.layout.list_item, null);

		ViewHolder holder = new ViewHolder();
        
		holder.progressbar = (ProgressBar) view.findViewById(R.id.ProgressBar);
		holder.progressbar.setVisibility(View.GONE);
        
        holder.title = (TextView) view.findViewById(R.id.title);
        holder.text = (TextView) view.findViewById(R.id.text);
        holder.timesource = (TextView) view.findViewById(R.id.timesource);
        
       	holder.title.setTextSize(_App._Fontsize);
       	holder.text.setTextSize(_App._Fontsize);
       	holder.timesource.setTextSize(_App._Fontsize - 4);
        
       	holder.imagelayout = (LinearLayout) view.findViewById(R.id.image_left);
       	holder.icon = (ImageView) view.findViewById(R.id.icon_left);
    	
    	holder.itemline = (LinearLayout) view.findViewById(R.id.itemline);
    	holder.unread = (ImageView) view.findViewById(R.id.unreadimage);
    	holder.unread.setImageBitmap(mUnRead);
    	
    	holder.favorite = (ImageView) view.findViewById(R.id.favoriteindicate);
    	holder.favorite.setImageBitmap(mFav);

    	holder.conversation = (ImageView) view.findViewById(R.id.conversation);
    	holder.conversation.setImageBitmap(mConversation);

    	String screenname = cursor.getString(DBTweetsHelper.COL_SCREENNAME);
    	String iconurl = cursor.getString(DBTweetsHelper.COL_ICONURL);
    	
    	if(screenname.length() != 0 && _App._twitter != null){
    		holder.icon.setImageBitmap(_App._twitter.LoadIcon(mCtx._Handler, screenname, iconurl));
       	}
    	
    	view.setTag(holder);
    	
    	return view;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		
		ViewHolder holder = (ViewHolder) view.getTag();
		
		int position = cursor.getPosition();	
		
		String screenname = cursor.getString(DBTweetsHelper.COL_SCREENNAME);
		String text = cursor.getString(DBTweetsHelper.COL_TEXT);
		long time = cursor.getLong(DBTweetsHelper.COL_TIME);
		String source = cursor.getString(DBTweetsHelper.COL_SOURCE);
		String replyid = cursor.getString(DBTweetsHelper.COL_REPLYID);
		boolean favorite = cursor.getInt(DBTweetsHelper.COL_FAVORITE) == 0 ? false: true;
		String imageurl = cursor.getString(DBTweetsHelper.COL_ICONURL);
		int read = GetReadStatus(position);
		
		if (read == TweetsListActivity.READ_STATE_UNKNOW){
			read = TweetsListActivity.READ_STATE_UNREAD;
			mReadStatuses.set(position, read);
		}
	    
	    holder.itemline.setBackgroundResource(mListbackground);

       	holder.title.setTextColor(mtextviewcolor);
      	holder.timesource.setTextColor(mtextviewcolor);
       	holder.text.setTextColor(mtextviewcolor);
        
        String search = "@" + _App._Username;
        if(text.contains(search) == true){
        	holder.itemline.setBackgroundResource(mListbackgroundat);
        }

        if(screenname.equalsIgnoreCase(_App._Username) == true){
        	holder.itemline.setBackgroundResource(mListbackgroundmy);
        }
        
        if(position == mCtx._ListsMgr.GetCurrentThread()){
        	holder.itemline.setBackgroundResource(mListbackgroundselset);
           	
           	holder.title.setTextColor(mtextviewcolorselect);
          	holder.timesource.setTextColor(mtextviewcolorselect);
           	holder.text.setTextColor(mtextviewcolorselect);
        }

        holder.favorite.setVisibility(View.GONE);
        holder.conversation.setVisibility(View.GONE);
        holder.icon.setVisibility(View.VISIBLE);
        holder.progressbar.setVisibility(View.GONE);
        
    	if(read == TweetsListActivity.READ_STATE_READ){
    		holder.unread.setVisibility(View.INVISIBLE);
    	}else{
    		holder.unread.setVisibility(View.VISIBLE);
    	}
    	
       	if (favorite == true){
       		holder.favorite.setVisibility(View.VISIBLE);
       	}
       	
       	if(TextUtils.isEmpty(replyid) == false && replyid.matches("null") == false){
       		holder.conversation.setVisibility(View.VISIBLE);
       	}
       	
        if(_App._Displayicon == true){
        	holder.imagelayout.setVisibility(View.VISIBLE);

            holder.icon.setImageBitmap(mBlank);
            
 	        switch (mScrollState) {
 	        case OnScrollListener.SCROLL_STATE_IDLE:
 	        	if(screenname.length() != 0 && _App._twitter != null){
 	       			holder.icon.setImageBitmap(_App._twitter.LoadIcon(mCtx._Handler, screenname, imageurl));
 	       		}
 	        }
            
        }else{
        	holder.imagelayout.setVisibility(View.GONE);
        }

       	if (screenname.length() == 0){
        	holder.title.setText("");
        	holder.timesource.setText("");
        	holder.favorite.setVisibility(View.INVISIBLE);
        	holder.icon.setVisibility(View.INVISIBLE);
        	
        	if(mLoadingState == 2){
        		holder.progressbar.setVisibility(View.VISIBLE);
        		holder.text.setText("  Loading more tweets ...  ");
        	}else if (mLoadingState == 1){
            	holder.text.setText("Click here to load more tweets");
        	}else{
        		holder.text.setText(text);
        	}
        }else{
           	holder.title.setText(screenname);
           	holder.timesource.setText(TweetsListActivity.CreateTimeSource(time, source));
           	holder.text.setText(text);
        }
	}
	
	public void ReQuery(MatrixCursor c){
		if(c == null) return;
		changeCursor(c);
		mCursor = c;
	}
	
	public void SetScrollState(int state){
		mScrollState = state;
	}

    public void CleanReadStatuses(){
    	mReadStatuses.clear();
    }
    
    public void AddReadStatus(int read){
    	mReadStatuses.add(read);
    }
    
    public int GetReadStatus(int position){
    	if (position >= mReadStatuses.size() || position < 0 ) return TweetsListActivity.READ_STATE_READ;
    	return mReadStatuses.get(position);
    }
    
    public void SetReadStatus(int position, int read){
    	if (position >= mReadStatuses.size() || position < 0 ) return;
    	mReadStatuses.set(position, read);
    }

	public TwitterItem Get(int i){
		Cursor cursor = getCursor();
		if (cursor.moveToPosition(i) == false) return null;
		
		return new TwitterItem(
				cursor.getInt(DBTweetsHelper.COL_READ), 
				cursor.getString(DBTweetsHelper.COL_SCREENNAME), 
				cursor.getString(DBTweetsHelper.COL_TITLE), 
				cursor.getString(DBTweetsHelper.COL_TEXT), 
				cursor.getLong(DBTweetsHelper.COL_TIME), 
				cursor.getString(DBTweetsHelper.COL_SOURCE), 
				cursor.getLong(DBTweetsHelper.COL_ID), 
				cursor.getString(DBTweetsHelper.COL_REPLYID), 
				cursor.getInt(DBTweetsHelper.COL_FAVORITE) == 0 ? false: true, 
				cursor.getInt(DBTweetsHelper.COL_FOLLOWING) == 0 ? false: true, 
				cursor.getString(DBTweetsHelper.COL_ICONURL), 
				cursor.getInt(DBTweetsHelper.COL_TYPE), 
				cursor.getString(DBTweetsHelper.COL_ACCOUNT),
				cursor.getString(DBTweetsHelper.COL_QUERY));
	}
	
	public void SetLoadingItem(){
		mLoadingState = 1;
		notifyDataSetChanged();
	}
	
	public void SetStartLoadingItem(){
		mLoadingState = 2;
		notifyDataSetChanged();
	}
	
	public long GetLong(int position, int cloumIndex){
		Cursor c = getCursor();
		if(c.moveToPosition(position)){
			return c.getLong(cloumIndex);
		}
		return -1;
	}
	
	public int GetInt(int position, int cloumIndex){
		Cursor c = getCursor();
		if(c.moveToPosition(position)){
			return c.getInt(cloumIndex);
		}
		return -1;
	}
	
	public void Clear(){
	}
	
	public void Remove(int i){
	}	

	public void addThread(TwitterItem item){
		Object[] rowObject = new Object[]{
				item.mID,
				item.mScreenname,
				item.mTitle,
				item.mText,
				item.mTime,
				item.mID,
				item.mSource,
				item.mReplyID,
				item.mFavorite==false?0:1,
				item.mFollowing==false?0:1,
				item.mImageurl,
				item.mType,
				item.mRead,
				item.mAccount,
				item.mQuery
		};
		mCursor.addRow(rowObject);
	}
	
	/*
    public void addThread(int read, String screenname, String title, String text, long time, String source, long id, String replyid, boolean fav, boolean following, String iconrui, boolean append){
    }
    */
	
	public final static Object[] ClickCursorMessage = {0,"","","Click here to load more tweets",0,0,"","null",0,0,"",0,2,"",""};

    public static MatrixCursor ClickCursor = new MatrixCursor(DBTweetsHelper.COLUMS);
    static {
    	ClickCursor.addRow(ClickCursorMessage);
    }
}
